﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace LiveLinq.Internal
{
	sealed class FirstQueryResultWithPredicate<TSource> : ObservableSingleQueryResultBase<TSource, TSource>
	{
		TSource _value;
		readonly Func<TSource, bool> _predicate;
		
		public FirstQueryResultWithPredicate(IEnumerable<TSource> source, Func<TSource, bool> predicate) : base(source)
		{
			_predicate = predicate;
			OnSourceReset();
		}
		
		protected override void OnSourceReset()
		{
			foreach (var item in _attached)
			{
				DetachItem(item);
			}
			
			_attached.Clear();
			
			bool macthFind = false;		
			foreach (var item in _source)
			{
				if(_predicate(item))
				{
					macthFind = true;
					_value = item;
				}
				AttachItem(item);
			}
			if(!macthFind)
			{
				throw new InvalidOperationException("NoMatch");
			}
		}
		
		protected override void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			OnSourceReset();
		}
		
		public override TSource Value {
			get { return _value; }
			set { throw new NotImplementedException(); }
		}
	}
}
